﻿#region Using Declaration

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Xml;
using System.Xml.Linq;

#endregion Using Declaration

namespace T4_Eind_programma
{
    public class FileIO
    {
        #region Variable Declaration

        private const string directoryFiles = "/Files/";
        private const string fileNameCSV = "tags.csv";
        private const string fileNameDoeltanken = "Doeltanken.xml";
        private const string fileNameOEE = "OEE.xml";
        private const string fileNameOrder = "Order.xml";
        private const string fileNameRemovedMengbatches = "Mengbatch.xml";
        private string location;

        #endregion Variable Declaration

        #region Properties

        public string FileNameCSV
        {
            get { return fileNameCSV; }
        }

        public string FileNameOEE
        {
            get { return fileNameOEE; }
        }

        public string FileNameOrder
        {
            get { return fileNameOrder; }
        }

        public string FileNameRemovedMengbatches
        {
            get { return fileNameRemovedMengbatches; }
        }

        public string Location
        {
            get { return location; }
        }

        #endregion Properties

        #region Constructor

        public FileIO()
        {
            location = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + directoryFiles;
            if (!Directory.Exists(location))
                Directory.CreateDirectory(location);
        }

        #endregion Constructor

        #region Checks

        public bool CheckInfoForWrite(ItemInfo item)
        {
            bool write = true;
            try
            {
                if (item.FilteredName.Contains("DB_") ||
                    item.FilteredName.Contains("#") ||
                    item.FilteredName.Contains("FB") ||
                    item.FilteredName.Contains("DB7") ||
                    item.FilteredName.Contains("DB4") ||
                    item.FilteredName.Contains("DB2") ||
                    item.FilteredName.Contains("DB10") ||
                    item.FilteredName.Contains("DB Com") ||
                    item.FilteredName.Contains("DB349") ||
                    item.FilteredName.Contains("DB351")
                    )
                    write = false;
            }
            catch (Exception)
            {
            }

            return write;
        }

        public bool CheckStringForWrite(string item)
        {
            bool write = true;
            try
            {
                if (item.Contains("DB_") ||
                    item.Contains("#") ||
                    item.Contains("FB") ||
                    item.Contains("DB7") ||
                    item.Contains("DB4") ||
                    item.Contains("DB2") ||
                    item.Contains("DB10") ||
                    item.Contains("DB Com") ||
                    item.Contains("DB349") ||
                    item.Contains("DB351")||
                    item.Contains("DB11") ||
                    item.Contains("PUT")
                    )
                    write = false;
            }
            catch (Exception)
            {
            }

            return write;
        }

        #endregion Checks

        #region Read

        public List<string> ParseCSV(string folderName, string fileName)
        {
            using (var reader = new StreamReader(File.OpenRead(folderName + fileName)))
            {
                var field2 = new List<string>();
                while (!reader.EndOfStream)
                {
                    var line = reader.ReadLine();
                    var values = line.Split(',');
                    string trimmed = values[1].Trim('"');
                    if (CheckStringForWrite(trimmed) == true)
                        field2.Add(values[1].Trim('"'));
                }
                return field2;
            }
        }

        public List<Doeltank> ReadDoeltanken()
        {
            var tanken = new List<Doeltank>();

            try
            {
                using (XmlReader reader = XmlReader.Create(location + fileNameDoeltanken))
                {
                    XDocument x = XDocument.Load(reader);
                    var oeeTable = x.Descendants("Tanken");
                    foreach (var tank in oeeTable)
                    {
                        foreach (XElement item in tank.Descendants("Tank"))
                        {
                            tanken.Add(new Doeltank(Convert.ToInt32(item.Attribute("Nummer").Value))
                            {
                                VorigeAantalVaten = Convert.ToInt32(item.Attribute("Aantal_vaten").Value),
                                HuidigeSmaak = new Smaak((item.Attribute("Huidige_Smaak").Value))
                            });
                        }
                    }
                    reader.Close();
                }
            }
            catch (Exception ex)
            {
                if (ex is XmlException)
                    File.Delete(location + fileNameOEE);
            }
            return tanken;
        }

        public List<OEEItem> ReadOEE()
        {
            var oeeList = new List<OEEItem>();
            try
            {
                if (!File.Exists(location + fileNameOEE))
                    File.Create(location + fileNameOEE);

                using (XmlReader reader = XmlReader.Create(location + fileNameOEE))
                {
                    XDocument x = XDocument.Load(reader);

                    var oeeTable = x.Descendants("OEEItem");
                    foreach (var oeeItem in oeeTable)
                    {
                        var apparatenLijst = new BindingList<ItemInfo>();
                        var outputs = oeeItem.Descendants("Outputs");
                        foreach (XElement output in outputs.Descendants())
                        {
                            apparatenLijst.Add(new ItemInfo(output.Attribute("Naam").Value)
                            {
                                ElapsedTime = Convert.ToDateTime(output.Attribute("TijdActief").Value),
                                Effectiviteit = Convert.ToInt32((output.Attribute("Effectiviteit").Value).Trim('%'))
                            });
                        }
                        oeeList.Add(new OEEItem(
                            Convert.ToDateTime(oeeItem.Element("Sessie_Datum").Value),
                            apparatenLijst,
                            Convert.ToDateTime(oeeItem.Element("Total_Time").Value),
                            Convert.ToDateTime(oeeItem.Element("Total_Active_Time").Value),
                             Convert.ToDateTime(oeeItem.Element("Total_InActive_Time").Value)));
                        var redenen = oeeItem.Descendants("Redenen_van_Stilstaan");
                        foreach (XElement reden in redenen.Descendants())
                        {
                            oeeList[oeeList.Count - 1].RedenLijst.Add(new RedenInactiviteit(reden.Attribute("Text").Value, Convert.ToDateTime(reden.Attribute("Tijd").Value), Convert.ToDateTime(reden.Attribute("TijdInactief").Value)));
                        }
                    }
                    reader.Close();
                }
            }
            catch (Exception ex)
            {
                if (ex is XmlException)
                    File.Delete(location + fileNameOEE);
            }
            return oeeList;
        }

        public BindingList<Order> ReadOrderList(string folderName, string fileName)
        {
            var orderList = new BindingList<Order>();
            try
            {
                if (File.Exists(folderName + fileName))
                {
                    if (File.Exists(location + fileNameOrder) && new FileInfo(location + fileNameOrder).Length < 3)
                    {
                        File.Delete(location + fileNameOrder);
                        File.Create(location + fileNameOrder);
                        return orderList;
                    }
                    using (XmlReader reader = XmlReader.Create(folderName + fileName))
                    {
                        XDocument x = XDocument.Load(reader);
                        // laat alleen elementen zien waar de naam Order is

                        var orderTables = x.Descendants("Order");

                        foreach (var order in orderTables)
                        {
                            orderList.Add(new Order(
                                Convert.ToInt32(order.Attribute("Nummer").Value), order.Attribute("Naam").Value, Convert.ToBoolean(order.Attribute("Klaar").Value)));

                            var mengbatchTables = order.Descendants("Mengbatch");

                            foreach (var mengbatch in mengbatchTables)
                            {
                                var status = mengbatch.Attribute("Status").Value;
                                if (status != null || status.Length < 2)
                                    status = "Inactief";
                                var temp = mengbatch.Attribute("Doeltank").Value.Split(',');
                                var doeltankList = new List<Doeltank>();
                                foreach (var item in temp)
                                {
                                    if (!String.IsNullOrWhiteSpace(item) && !String.IsNullOrEmpty(item))
                                        doeltankList.Add(new Doeltank(Convert.ToInt32(item)));
                                }
                                orderList[orderList.Count - 1].MengbatchList.Add(new Mengbatch(
                                           Convert.ToInt32(mengbatch.Attribute("Nummer").Value),
                                           mengbatch.Attribute("Productcode").Value, new Smaak(
                                           mengbatch.Attribute("Smaak").Value),
                                           Convert.ToInt32(mengbatch.Attribute("HoeveelheidVaten").Value),
                                           Convert.ToInt32(mengbatch.Attribute("Siroop").Value),
                                           Convert.ToInt32(mengbatch.Attribute("Mengtijd").Value),
                                           Convert.ToBoolean(mengbatch.Attribute("Verwarmen").Value),
                                           Convert.ToBoolean(mengbatch.Attribute("Handmatig").Value), doeltankList,
                                           Convert.ToBoolean(mengbatch.Attribute("Klaar").Value),
                                Convert.ToInt32(mengbatch.Attribute("VerwarmTijd").Value)) { Status = status });

                                var vulbatchTables = mengbatch.Descendants("Vulbatch");
                                foreach (var vulbatch in vulbatchTables)
                                {
                                    orderList[orderList.Count - 1].MengbatchList[orderList[orderList.Count - 1].MengbatchList.Count - 1].VulbatchList.Add(new Vulbatch(
                                           Convert.ToInt32(vulbatch.Attribute("Nummer").Value),
                                           Convert.ToInt32(vulbatch.Attribute("Mengbatch").Value),
                                           Convert.ToInt32(vulbatch.Attribute("Aantalvaten").Value),
                                           Convert.ToBoolean(vulbatch.Attribute("Klaar").Value),
                                          new Doeltank(Convert.ToInt32(vulbatch.Attribute("Doeltank").Value))
                                          )
                                          {
                                              RestVaten = Convert.ToInt32(vulbatch.Attribute("Rest_Vaten").Value),
                                              GevuldeVaten = Convert.ToInt32(vulbatch.Attribute("Gevulde_Vaten").Value)
                                          }
                                          );
                                    var apparaten = vulbatch.Attribute("Apparaten").Value;
                                    var splitter = apparaten.Split(' ');
                                    for (int z = 0; z < splitter.Length - 1; z++)
                                    {
                                        orderList[orderList.Count - 1].MengbatchList[orderList[orderList.Count - 1].MengbatchList.Count - 1].VulbatchList[z].GebruikteApparaten.Add(splitter[z]);
                                    }
                                }
                            }
                        }

                        reader.Close();
                    }
                }
            }
            catch (Exception)
            {
                if (File.Exists(location + fileNameOrder))
                {
                    File.Delete(location + fileNameOrder);
                }
            }
            return orderList;
        }

        #endregion Read

        #region Write

        public void WriteDoeltanken(List<Doeltank> doelTanken)
        {
            try
            {
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;
                settings.CloseOutput = true;
                using (XmlWriter writer = XmlWriter.Create(location + fileNameDoeltanken, settings))
                {
                    writer.WriteStartDocument();
                    writer.WriteStartElement("Tanken");
                    foreach (var item in doelTanken)
                    {
                        writer.WriteStartElement("Tank");
                        writer.WriteAttributeString("Nummer", item.Nummer.ToString());
                        if (item.HuidigeSmaak != null)
                            writer.WriteAttributeString("Huidige_Smaak", item.HuidigeSmaak.Naam.ToString());
                        else
                            writer.WriteAttributeString("Huidige_Smaak", null);
                        writer.WriteAttributeString("Aantal_vaten", item.VorigeAantalVaten.ToString());

                        writer.WriteEndElement();
                    }
                    writer.WriteEndDocument();
                    writer.Flush();
                    writer.Close();
                }
            }
            catch (Exception)
            {
            }
        }

        public void WriteOEE(List<OEEItem> oeeItemList)
        {
            try
            {
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;
                settings.CloseOutput = true;
                using (XmlWriter writer = XmlWriter.Create(location + fileNameOEE, settings))
                {
                    writer.WriteStartDocument();
                    writer.WriteStartElement("OEE_Overzicht");
                    foreach (var item in oeeItemList)
                    {
                        writer.WriteStartElement("OEEItem");
                        writer.WriteElementString("Sessie_Datum", item.SessieDatum.ToString());
                        writer.WriteElementString("Total_Time", item.TotaleTijdVanSessie.ToString());
                        writer.WriteElementString("Total_Active_Time", item.TotaleTijdActiefVanSessie.ToString());
                        writer.WriteElementString("Total_InActive_Time", item.TotaleTijdActiefVanSessie.ToString());

                        writer.WriteStartElement("Outputs");
                        foreach (var infoItem in item.ApparatenLijst)
                        {
                            if (CheckInfoForWrite(infoItem) == true)
                            {
                                writer.WriteStartElement("Output");
                                writer.WriteAttributeString("Naam", infoItem.Name.Trim());
                                writer.WriteAttributeString("TijdActief", infoItem.ActiveTimer.Elapsed.ToString());
                                writer.WriteAttributeString("Effectiviteit", infoItem.Effectiviteit.ToString());
                                writer.WriteEndElement();
                            }
                        }
                        writer.WriteEndElement();
                        writer.WriteStartElement("Redenen_van_Stilstaan");
                        foreach (var reden in item.RedenLijst)
                        {
                            writer.WriteStartElement("Reden");
                            writer.WriteAttributeString("Tijd", reden.BeginTijd.ToString());
                            writer.WriteAttributeString("Text", reden.Reden);
                            writer.WriteAttributeString("TijdInactief", reden.TijdInactiefDateTime.ToString());
                            writer.WriteEndElement();
                        }
                        writer.WriteEndElement();
                        writer.WriteEndElement();
                    }
                    writer.WriteEndDocument();
                    writer.Flush();
                    writer.Close();
                }
            }
            catch (Exception)
            {
            }
        }

        public void WriteOrderList(string folderName, string filename, BindingList<Order> orderList)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.CloseOutput = true;
            if (File.Exists(folderName + filename))
            {
                File.Delete(folderName + filename);
            }
            using (XmlWriter writer = XmlWriter.Create(folderName + filename, settings))
            {
                writer.WriteStartDocument();
                writer.WriteStartElement("Orderlist");
                foreach (Order orderItem in orderList)
                {
                    writer.WriteStartElement("Order");
                    writer.WriteAttributeString("Nummer", orderItem.Nummer.ToString());
                    writer.WriteAttributeString("Naam", orderItem.Naam);
                    writer.WriteAttributeString("Klaar", orderItem.Klaar.ToString());

                    foreach (Mengbatch mengbatchItem in orderItem.MengbatchList)
                    {
                        writer.WriteStartElement("Mengbatch");

                        writer.WriteAttributeString("Nummer", mengbatchItem.Nummer.ToString());
                        writer.WriteAttributeString("Productcode", mengbatchItem.Productcode);
                        writer.WriteAttributeString("Smaak", mengbatchItem.Smaak.Naam);
                        writer.WriteAttributeString("HoeveelheidVaten", mengbatchItem.Hoeveelheid.ToString());
                        writer.WriteAttributeString("Siroop", mengbatchItem.SiroopPercentage.ToString());
                        writer.WriteAttributeString("Mengtijd", mengbatchItem.Mengtijd.ToString());
                        writer.WriteAttributeString("Verwarmen", mengbatchItem.Verwarmen.ToString());
                        writer.WriteAttributeString("VerwarmTijd", mengbatchItem.VerwarmTijd.ToString());
                        writer.WriteAttributeString("Handmatig", mengbatchItem.Handmatig.ToString());

                        if (mengbatchItem.Doeltank.Count > 1)
                        {
                            writer.WriteAttributeString("Doeltank", mengbatchItem.Doeltank[0].Nummer + "," + mengbatchItem.Doeltank[1].Nummer);
                        }
                        else
                        {
                            writer.WriteAttributeString("Doeltank", mengbatchItem.Doeltank[0].Nummer.ToString());
                        }

                        writer.WriteAttributeString("Klaar", mengbatchItem.Klaar.ToString());
                        writer.WriteAttributeString("Status", mengbatchItem.Status);
                        foreach (Vulbatch vulbatchItem in mengbatchItem.VulbatchList)
                        {
                            writer.WriteStartElement("Vulbatch");

                            writer.WriteAttributeString("Nummer", vulbatchItem.Nummer.ToString());
                            writer.WriteAttributeString("Mengbatch", vulbatchItem.MengbatchNummer.ToString());
                            writer.WriteAttributeString("Aantalvaten", vulbatchItem.AantalVaten.ToString());
                            writer.WriteAttributeString("Klaar", vulbatchItem.Klaar.ToString());
                            writer.WriteAttributeString("Doeltank", vulbatchItem.Doeltank.Nummer.ToString());
                            writer.WriteAttributeString("Gevulde_Vaten", vulbatchItem.GevuldeVaten.ToString());
                            writer.WriteAttributeString("Rest_Vaten", vulbatchItem.RestVaten.ToString());
                            writer.WriteAttributeString("Smaak", mengbatchItem.Smaak.Naam);
                            writer.WriteAttributeString("SiroopPct", mengbatchItem.SiroopPercentage.ToString());
                            string apparaten = "";
                            foreach (string item in vulbatchItem.GebruikteApparaten)
                            {
                                apparaten += item + " ";
                            }
                            writer.WriteAttributeString("Apparaten", vulbatchItem.Klaar.ToString());
                            writer.WriteEndElement();
                        }
                        writer.WriteEndElement();
                    }
                    writer.WriteEndElement();
                }
                writer.Flush();
                writer.Close();
            }
        }

        #endregion Write
    }
}

//svn checkout https://t4thesequeal.googlecode.com/svn/trunk/ t4thesequeal --username jeffreypanneman@gmail.com
//https://t4thesequeal.googlecode.com/svn/branches/T4 Eind programma/
//DJ5mw4Xn2NJ7